package com.zyl.config;

import com.zyl.pojo.User;
import com.zyl.service.UserService;
import com.zyl.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: Zyl
 * @Param:
 * @return:
 * @Description: shiro中的realm指定类
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        Subject subject= SecurityUtils.getSubject();
        User CurrentUser = (User) subject.getPrincipal();
        return info;
    }



    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken= (UsernamePasswordToken) token;
        User user = userService.queryUserByUsername(userToken.getUsername());
        if (user==null){
            return null;
        }
        /**
         * @Author: Zyl
         * @Param:
         * @return:
         * @Description: 最后登陆时间
         */
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setRecentlyLanded(sdf.format(d));
        System.out.println(user);
        userService.updateUser(user);
        //密码 shiro自己验证
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}